package ar.com.ford.it.fullEconomics.view.action;

import java.util.Collection;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.util.MessageResources;
import ar.com.ford.it.fullEconomics.exception.FullEconomicsException;
import ar.com.ford.it.fullEconomics.facade.CommodityFacade;
import ar.com.ford.it.fullEconomics.facade.CostStructureFacade;
import ar.com.ford.it.fullEconomics.facade.PaymentPolicyFacade;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesc05Itemcatgry;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesc06Item;
import ar.com.ford.it.fullEconomics.persistence.dto.Teese04Paypolicy;
import ar.com.ford.it.fullEconomics.persistence.dto.Teese05Paypolvers;
import ar.com.ford.it.fullEconomics.persistence.dto.Teess01Supplier;
import ar.com.ford.it.fullEconomics.struct.FullEconomicWrapStruct;
import ar.com.ford.it.fullEconomics.struct.PaymentPolicyDisplayStruct;
import ar.com.ford.it.fullEconomics.view.form.PaymentPolicyForm;
import ar.com.ford.it.fullEconomics.wslx.FullEconomicsWslxUser;
import ar.com.ford.it.webengine.facade.FacadeProvider;
import ar.com.ford.it.webengine.struts.AbstractBaseAction;
import ar.com.ford.it.webengine.struts.FordActionMapping;
import ar.com.ford.it.webengine.websession.WebSession;

public class PaymentPolicyAction extends AbstractBaseAction {

    /**
     * Setea el mensaje de "busqueda sin resultados" cuando la busqueda no trae
     * resultados
     * 
     * @param request
     * Request donde se guarda el mensaje
     */
    private void searchWithNoResults(HttpServletRequest request) {
        ActionMessages am = new ActionMessages();
        MessageResources messageResources = (MessageResources) getResources(request);

        am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
                "customMessage", messageResources
                        .getMessage("message.noResults")));
        saveMessages(request, am);
    }

    /**
     * carga los valores iniciales de la pagina
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward initPage(FordActionMapping mapping,
                                  ActionForm actionForm,
                                  HttpServletRequest request,
                                  HttpServletResponse response,
                                  WebSession webSession, ActionMessages msgs,
                                  ActionMessages warns, ActionMessages errorMsgs) {

        ActionMessages am = new ActionMessages();
        FullEconomicsWslxUser user = (FullEconomicsWslxUser) webSession
                .getUser();
        PaymentPolicyForm form = (PaymentPolicyForm) actionForm;
        form.resetForm();
        CommodityFacade commFacade = (CommodityFacade) FacadeProvider
                .getFacade(request, CommodityFacade.class);
        CostStructureFacade cstrFacade = (CostStructureFacade) FacadeProvider
                .getFacade(request, CostStructureFacade.class);
        request.getSession().setAttribute("partClassColl",
                commFacade.getPartClases());
        FullEconomicWrapStruct fullEconomic = (FullEconomicWrapStruct) request
                .getAttribute("fullEconomicWrap");
        form.setFullEconomic(fullEconomic);
        String forward = "success";
        if (form.getFullEconomic() != null) {
            form.setSupplierClass(fullEconomic.getSubCostStrVers()
                    .getTeesc01Coststruct().getTeess01Supplier()
                    .getEess01SupplierClassCodeC());
            form.setSupplierCode(fullEconomic.getSubCostStrVers()
                    .getTeesc01Coststruct().getTeess01Supplier()
                    .getEess01SupplierCodeC());
            form.setItemCategory(fullEconomic.getRowSelected()
                    .getSubCostStrItem().getTeesc06Item()
                    .getTeesc05Itemcatgry().getEesc05ItemcatgryNumberK()
                    .toString());
            form.setItem(fullEconomic.getRowSelected().getSubCostStrItem()
                    .getTeesc06Item().getEesc06ItemNumberK().toString());
            forward = "find";
        }
        try {
            request.getSession().setAttribute(
                    "commodityColl",
                    commFacade.findCommodities(null, null, user
                            .getTeesg01Plant()));
            request.getSession().setAttribute("ItemCategoryColl",
                    cstrFacade.findAllItemCategories(user.getTeesg01Plant()));
            request.getSession().setAttribute("itemColl",
                    cstrFacade.findApprovedItems(user.getTeesg01Plant(), "-1"));
        } catch (FullEconomicsException e) {
            am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                    .getMessageResource()));
            saveErrors(request, am);
        }
        return mapping.findForward(forward);
    }

    /**
     * busca los items de cierta item category
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward findItems(FordActionMapping mapping,
                                   ActionForm actionForm,
                                   HttpServletRequest request,
                                   HttpServletResponse response,
                                   WebSession webSession, ActionMessages msgs,
                                   ActionMessages warns,
                                   ActionMessages errorMsgs) {

        ActionMessages am = new ActionMessages();
        FullEconomicsWslxUser user = (FullEconomicsWslxUser) webSession
                .getUser();
        CostStructureFacade cstrFacade = (CostStructureFacade) FacadeProvider
                .getFacade(request, CostStructureFacade.class);
        try {
            String itemCat = request.getParameter("itemCategory");
            Collection itemList = cstrFacade.findApprovedItems(user
                    .getTeesg01Plant(), itemCat);
            request.getSession().setAttribute("itemColl", itemList);
        } catch (FullEconomicsException e) {
            am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                    .getMessageResource()));
            saveErrors(request, am);
        }
        return mapping.findForward("success");
    }

    /**
     * Busca las politicas de pago, segun el filtro especificado
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward findPaymentPolicy(FordActionMapping mapping,
                                           ActionForm actionForm,
                                           HttpServletRequest request,
                                           HttpServletResponse response,
                                           WebSession webSession,
                                           ActionMessages msgs,
                                           ActionMessages warns,
                                           ActionMessages errorMsgs) {

        ActionMessages am = new ActionMessages();
        FullEconomicsWslxUser user = (FullEconomicsWslxUser) webSession
                .getUser();
        PaymentPolicyForm form = (PaymentPolicyForm) actionForm;
        PaymentPolicyFacade facade = (PaymentPolicyFacade) FacadeProvider
                .getFacade(request, PaymentPolicyFacade.class);
        Collection<PaymentPolicyDisplayStruct> res = null;

        try {
            Teese05Paypolvers findPayPolVers = new Teese05Paypolvers();
            Teese04Paypolicy findPayPol = new Teese04Paypolicy();
            Teess01Supplier supplier = new Teess01Supplier();
            Teesc05Itemcatgry itemCat = new Teesc05Itemcatgry();
            Teesc06Item item = new Teesc06Item();

            supplier.setEess01SupplierClassCodeC(form.getSupplierClass());
            supplier.setEess01SupplierCodeC(form.getSupplierCode());
            itemCat.setEesc05ItemcatgryNumberK(new Integer(form
                    .getItemCategory()));
            item.setEesc06ItemNumberK(new Integer(form.getItem()));
            findPayPol.setTeesc05Itemcatgry(itemCat);
            findPayPol.setTeesc06Item(item);
            findPayPol.setTeess01Supplier(supplier);

            findPayPolVers.setTeese04Paypolicy(findPayPol);
            findPayPolVers.setEese05PlantCodeC(user.getTeesg01Plant());
            if (form.getAprovedOnesOnly().equals("true"))
                res = facade.findLastAprovedPaymentPolicies(findPayPolVers);
            else
                res = facade.findPaymentPolicies(findPayPolVers);
            if (res.isEmpty()) {
                searchWithNoResults(request);
            }
        } catch (FullEconomicsException e) {
            am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                    .getMessageResource()));
            saveErrors(request, am);
        }
        form.setPayPolVersCol(res);
        return mapping.findForward("success");
    }

    /**
     * lleva al detalle de payment policy
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward paymentPolicyVersionDetail(
                                                    FordActionMapping mapping,
                                                    ActionForm actionForm,
                                                    HttpServletRequest request,
                                                    HttpServletResponse response,
                                                    WebSession webSession,
                                                    ActionMessages msgs,
                                                    ActionMessages warns,
                                                    ActionMessages errorMsgs) {

        PaymentPolicyForm form = (PaymentPolicyForm) actionForm;
        Teese05Paypolvers payPolVers = form.getPayPolVersSelected();
        request.setAttribute("payPolVersSelected", payPolVers);
        request.setAttribute("fullEconomic", form.getFullEconomic());
        return mapping.findForward("success");
    }

    /**
     * propone la politica de pago seleccionada
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward propose(FordActionMapping mapping,
                                 ActionForm actionForm,
                                 HttpServletRequest request,
                                 HttpServletResponse response,
                                 WebSession webSession, ActionMessages msgs,
                                 ActionMessages warns, ActionMessages errorMsgs) {

        ActionMessages am = new ActionMessages();
        FullEconomicsWslxUser user = (FullEconomicsWslxUser) webSession
                .getUser();
        PaymentPolicyForm form = (PaymentPolicyForm) actionForm;
        PaymentPolicyFacade facade = (PaymentPolicyFacade) FacadeProvider
                .getFacade(request, PaymentPolicyFacade.class);
        Teese05Paypolvers payPolVers = form.getPayPolVersSelected();
        try {
            facade.proposePaymentPolicy(payPolVers, user);
        } catch (FullEconomicsException e) {
            am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                    .getMessageResource()));
            saveErrors(request, am);
        }
        return mapping.findForward("success");
    }

    /**
     * se aprueva la politica de pago selecionada
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward approve(FordActionMapping mapping,
                                 ActionForm actionForm,
                                 HttpServletRequest request,
                                 HttpServletResponse response,
                                 WebSession webSession, ActionMessages msgs,
                                 ActionMessages warns, ActionMessages errorMsgs) {

        ActionMessages am = new ActionMessages();
        FullEconomicsWslxUser user = (FullEconomicsWslxUser) webSession
                .getUser();
        PaymentPolicyForm form = (PaymentPolicyForm) actionForm;
        PaymentPolicyFacade facade = (PaymentPolicyFacade) FacadeProvider
                .getFacade(request, PaymentPolicyFacade.class);
        Teese05Paypolvers payPolVers = form.getPayPolVersSelected();
        try {
            facade.approvePaymentPolicy(payPolVers, user);
        } catch (FullEconomicsException e) {
            am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                    .getMessageResource()));
            saveErrors(request, am);
        }
        return mapping.findForward("success");
    }

    /**
     * se aprueva la politica de pago selecionada
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward approveAll(FordActionMapping mapping,
                                    ActionForm actionForm,
                                    HttpServletRequest request,
                                    HttpServletResponse response,
                                    WebSession webSession, ActionMessages msgs,
                                    ActionMessages warns,
                                    ActionMessages errorMsgs) {

        ActionMessages am = new ActionMessages();
        FullEconomicsWslxUser user = (FullEconomicsWslxUser) webSession
                .getUser();
        PaymentPolicyForm form = (PaymentPolicyForm) actionForm;
        PaymentPolicyFacade facade = (PaymentPolicyFacade) FacadeProvider
                .getFacade(request, PaymentPolicyFacade.class);
        Collection<PaymentPolicyDisplayStruct> payPolVersCol = form
                .getPayPolVersCol();
        try {
            facade.approveAllPaymentPolicy(payPolVersCol, user);
        } catch (FullEconomicsException e) {
            am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                    .getMessageResource()));
            saveErrors(request, am);
        }
        return mapping.findForward("success");
    }

    /**
     * se aprueva la politica de pago selecionada
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward deletePaymentPolicyVersion(
                                                    FordActionMapping mapping,
                                                    ActionForm actionForm,
                                                    HttpServletRequest request,
                                                    HttpServletResponse response,
                                                    WebSession webSession,
                                                    ActionMessages msgs,
                                                    ActionMessages warns,
                                                    ActionMessages errorMsgs) {

        ActionMessages am = new ActionMessages();
        FullEconomicsWslxUser user = (FullEconomicsWslxUser) webSession
                .getUser();
        PaymentPolicyForm form = (PaymentPolicyForm) actionForm;
        PaymentPolicyFacade facade = (PaymentPolicyFacade) FacadeProvider
                .getFacade(request, PaymentPolicyFacade.class);
        Teese05Paypolvers payPolVers = form.getPayPolVersSelected();
        try {
            facade.deletePaymentPolicyVersion(payPolVers);
        } catch (FullEconomicsException e) {
            am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                    .getMessageResource()));
            saveErrors(request, am);
        }
        return mapping.findForward("success");
    }

    /**
     * lleva seteal el pp seleccionado y regresa a full economics
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward setPpInFullEconomic(FordActionMapping mapping,
                                             ActionForm actionForm,
                                             HttpServletRequest request,
                                             HttpServletResponse response,
                                             WebSession webSession,
                                             ActionMessages msgs,
                                             ActionMessages warns,
                                             ActionMessages errorMsgs) {

        PaymentPolicyForm form = (PaymentPolicyForm) actionForm;
        Teese05Paypolvers payPolVers = form.getPayPolVersSelected();
        form.getFullEconomic().getRowSelected().setPayPolVers(payPolVers);
        request.setAttribute("fullEconomicWrap", form.getFullEconomic());
        return mapping.findForward("success");
    }

}
